package com.gzy.fisherybackend.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.gzy.fisherybackend.service.HdfsService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private HdfsService hdfsService;

    /**
     * 上传文件到HDFS
     */
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String hdfsPath = hdfsService.uploadFile(file);
            return ResponseEntity.ok("文件上传成功: " + hdfsPath);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 从HDFS下载文件
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("path") String hdfsPath) {
        try {
            byte[] fileContent = hdfsService.downloadFile(hdfsPath);
            
            // 从路径中提取文件名
            String fileName = hdfsPath.substring(hdfsPath.lastIndexOf('/') + 1);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            
            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (IOException e) {
            log.error("文件下载失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     * 删除HDFS上的文件
     */
    @DeleteMapping
    public ResponseEntity<String> deleteFile(@RequestParam("path") String hdfsPath) {
        try {
            boolean deleted = hdfsService.deleteFile(hdfsPath);
            if (deleted) {
                return ResponseEntity.ok("文件删除成功");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在或删除失败");
            }
        } catch (IOException e) {
            log.error("文件删除失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件删除失败: " + e.getMessage());
        }
    }
} 